from rest_framework import serializers

from goods.models import SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex
from django_redis import get_redis_connection


class SKUSSerialziers(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSeializer(HaystackSerializer):
    object = SKUSSerialziers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerialzier(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # 验证  判断商品是否存在
    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    # 保存商品对象
    # def create(self, validated_data):
    #     # 获取当前用户
    #     user = self.context['request'].user
    #     sku_id = validated_data['sku_id']
    #     # 建立缓存链接
    #     conn = get_redis_connection('history')
    #     # 判断当前sku_id 是否存在与列表
    #     conn.lrem('history_%s' % user.id, 0, sku_id)
    #     # 写入缓存
    #     conn.lpush('history_%s' % user.id, sku_id)
    #     # 控制数量 0-4 为五个数据
    #     conn.ltrim('history_%s' % user.id, 0, 4)
    #     return validated_data
    def create(self, validated_data):
        user = self.context['request'].user
        sku_id = validated_data['sku_id']
        conn = get_redis_connection('history')
        pl = conn.pipeline()
        pl.lrem('history_%s'%user.id,0,sku_id)
        pl.lpush('history_%s'%user.id,sku_id)
        pl.ltrim('history_%s'%user.id,0,4)
        pl.execute()

        return validated_data